<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理 - AI故事生成器</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="/static/css/user_control.css">
    <link rel="stylesheet" href='/static/css/1.css'>
    <link rel="stylesheet" href="/static/css/header.css">
    <link rel="stylesheet" href="/static/css/footer.css">
    <script src="/static/js/header.js" defer></script>
    <style>
        /* 分页样式 */
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 30px;
            gap: 10px;
        }

        .page-link {
            display: inline-block;
            padding: 8px 16px;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            color: #007bff;
            text-decoration: none;
            transition: all 0.3s;
        }

        .page-link:hover {
            background-color: #e9ecef;
            border-color: #dee2e6;
        }

        .page-link.current {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }

        .loading, .error {
            text-align: center;
            padding: 40px;
            font-size: 18px;
            color: #666;
            grid-column: 1 / -1;
        }

        .loading {
            color: #007bff;
        }

        .error {
            color: #dc3545;
        }
    </style>
</head>
<body>
{% include 'header.html' %}
<input type="hidden" id="csrf-token" value="{{ csrf_token }}">
<main class="container">
    <div class="user-grid" id="userGrid">
        <!-- 用户卡片将通过JavaScript动态生成 -->
        {% for user in users %}
            <div class="note-card">
                <div class="tape"></div>
                <div class="card-header">
                    <img src="{{ '/static/img/default.jpg' }}" alt="头像" class="avatar">
                    <div class="user-info">
                        <h2>{{ user.name }}</h2>
                        <p>{{ user.email }}</p>
                    </div>
                </div>
                <div class="card-body">
                    <div class="info-row">
                        <span class="info-label">注册日期</span>
                        <span class="info-value">{{ user.registerDate|date:"Y-m-d" }}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">状态</span>
                        <span class="info-value">
                            {% if user.status == '启用' %}
                                <span class="status-badge status-enabled">已启用</span>
                            {% else %}
                                <span class="status-badge status-disabled">已禁用</span>
                            {% endif %}
                        </span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">身份</span>
                        <span class="info-value">
                        {% if user.role == '管理员' %}
                            <span class="status-badge role-admin">管理员</span>
                        {% elif user.role == '普通用户' %}
                            <span class="status-badge role-moderator">普通用户</span>
                        {% elif user.role == '作者' %}
                            <span class="status-badge role-vip">作者</span>
                        {% endif %}
                        </span>
                    </div>
                </div>
                <div class="card-footer">
                    {% if user.status == '启用' %}
                        <button class="action-btn disable-btn" data-user-id="{{ user.id }}">
                            <i class="fas fa-ban"></i> 禁用
                        </button>
                    {% else %}
                        <button class="action-btn enable-btn" data-user-id="{{ user.id }}">
                            <i class="fas fa-check-circle"></i> 启用
                        </button>
                    {% endif %}
                </div>
            </div>
        {% endfor %}
    </div>

    <!-- 分页控件 -->
    <div class="pagination" id="pagination">
        {% if page_obj.has_previous %}
            <a href="?page={{ page_obj.previous_page_number }}" class="page-link">上一页</a>
        {% endif %}

        {% for num in page_obj.paginator.page_range %}
            {% if page_obj.number == num %}
                <span class="page-link current">{{ num }}</span>
            {% else %}
                <a href="?page={{ num }}" class="page-link">{{ num }}</a>
            {% endif %}
        {% endfor %}

        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}" class="page-link">下一页</a>
        {% endif %}
    </div>
</main>

{% include 'footer.html' %}

<script>
    // 初始化变量
    let currentPage = {{ page_obj.number }};
    const totalPages = {{ page_obj.paginator.num_pages }};

    // 当DOM加载完成后执行
    document.addEventListener('DOMContentLoaded', function () {
        const userGrid = document.getElementById('userGrid');
        const paginationContainer = document.getElementById('pagination');

        // 事件委托处理分页点击
        paginationContainer.addEventListener('click', function (e) {
            if (e.target.classList.contains('page-link') && !e.target.classList.contains('current')) {
                e.preventDefault();
                const urlParams = new URLSearchParams(e.target.search);
                const page = urlParams.get('page') || parseInt(e.target.textContent);
                if (!isNaN(page) && page !== currentPage) {
                    loadPage(page);
                }
            }
        });

        // 事件委托处理状态切换按钮
        userGrid.addEventListener('click', function (e) {
            if (e.target.closest('.action-btn')) {
                const btn = e.target.closest('.action-btn');
                if (btn.classList.contains('disable-btn') || btn.classList.contains('enable-btn')) {
                    const userId = btn.dataset.userId;
                    toggleUserStatus(userId);
                }
            }
        });

        // 加载指定页码的用户数据
        function loadPage(page) {
            // 显示加载指示器
            userGrid.innerHTML = '<div class="loading">加载中...</div>';

            fetch(`?page=${page}`, {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    currentPage = data.current_page;
                    renderUsers(data.users);
                    renderPagination(data.total_pages, data.current_page);
                })
                .catch(error => {
                    console.error('加载用户数据时出错:', error);
                    userGrid.innerHTML = '<div class="error">加载失败，请刷新页面重试</div>';
                });
        }

        // 渲染用户卡片
        function renderUsers(users) {
            let usersHTML = '';

            users.forEach(user => {
                usersHTML += `
                <div class="note-card">
                    <div class="tape"></div>
                    <div class="card-header">
                        <img src="${user.avatar || '/static/img/default.jpg'}" alt="头像" class="avatar">
                        <div class="user-info">
                            <h2>${user.name}</h2>
                            <p>${user.email}</p>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="info-row">
                            <span class="info-label">注册日期</span>
                            <span class="info-value">${user.registerDate}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">状态</span>
                            <span class="info-value">
                                ${user.status === '启用' ?
                    '<span class="status-badge status-enabled">已启用</span>' :
                    '<span class="status-badge status-disabled">已禁用</span>'}
                            </span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">身份</span>
                            <span class="info-value">
                            ${user.role === '管理员' ?
                    '<span class="status-badge role-admin">管理员</span>' :
                    user.role === '普通用户' ?
                        '<span class="status-badge role-moderator">普通用户</span>' :
                        '<span class="status-badge role-vip">作者</span>'}
                            </span>
                        </div>
                    </div>
                    <div class="card-footer">
                        ${user.status === '启用' ?
                    `<button class="action-btn disable-btn" data-user-id="${user.id}">
                                <i class="fas fa-ban"></i> 禁用
                            </button>` :
                    `<button class="action-btn enable-btn" data-user-id="${user.id}">
                                <i class="fas fa-check-circle"></i> 启用
                            </button>`}
                    </div>
                </div>
            `;
            });

            userGrid.innerHTML = usersHTML;
        }

        // 渲染分页控件
        function renderPagination(totalPages, currentPage) {
            let paginationHTML = '';

            if (totalPages > 1) {
                // 上一页按钮
                if (currentPage > 1) {
                    paginationHTML += `<a href="?page=${currentPage - 1}" class="page-link">上一页</a>`;
                }

                // 页码按钮
                let startPage = Math.max(1, currentPage - 2);
                let endPage = Math.min(totalPages, startPage + 4);

                if (endPage - startPage < 4) {
                    startPage = Math.max(1, endPage - 4);
                }

                for (let i = startPage; i <= endPage; i++) {
                    if (i === currentPage) {
                        paginationHTML += `<span class="page-link current">${i}</span>`;
                    } else {
                        paginationHTML += `<a href="?page=${i}" class="page-link">${i}</a>`;
                    }
                }

                // 下一页按钮
                if (currentPage < totalPages) {
                    paginationHTML += `<a href="?page=${currentPage + 1}" class="page-link">下一页</a>`;
                }
            }

            paginationContainer.innerHTML = paginationHTML;
        }

        // 切换用户状态
        function toggleUserStatus(userId) {
            console.log("尝试切换用户状态，用户ID:", userId);

            const url = "{% url 'store_system:toggle_user_status' 0 %}".replace('0', userId);
            console.log("请求URL:", url);

            const csrfToken = getCookie('csrftoken');
            console.log("CSRF令牌:", csrfToken ? "已找到" : "未找到");

            fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': csrfToken,
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `user_id=${userId}`
            })
                .then(response => {
                    console.log("响应状态:", response.status, response.statusText);
                    if (!response.ok) {
                        throw new Error(`HTTP错误: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("响应数据:", data);
                    if (data.success) {
                        // 重新加载当前页面以更新状态
                        loadPage(currentPage);
                    } else {
                        alert('操作失败: ' + (data.error || data.message || '未知错误'));
                    }
                })
                .catch(error => {
                    console.error('切换用户状态时出错:', error);
                    alert('操作失败，请重试。查看控制台获取详细信息。');
                });
        }

        // 获取CSRF token
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    });
</script>
</body>
</html>